#include "dbconnection.h"

#include <QSqlField>
#include <QSqlDriver>

QSharedPointer<DbConnection> DbConnection::_instance;

DbConnection::DbConnection()
{
}

DbConnection::~DbConnection()
{
}

QSharedPointer<DbConnection> DbConnection::instance()
{
    if(_instance.isNull())
    {
        _instance = QSharedPointer<DbConnection>(new DbConnection);
    }
    return _instance;
}

bool DbConnection::setupConnection(Settings &settings)
{
    QSqlDatabase database = QSqlDatabase::addDatabase("QMYSQL");
    database.setHostName(settings.getDbServer());
    database.setDatabaseName(settings.getDbName());
    database.setUserName(settings.getDbUser());
    database.setPassword(settings.getDbPassword());
    return database.open();
}

QString DbConnection::escapeValue(QString &value)
{
    QSqlDatabase db = DbConnection::instance()->getDb();

    QSqlField field;
    field.setType(QVariant::String);
    field.setValue(value);

    return db.driver()->formatValue(field);
}

QSqlDatabase DbConnection::getDb()
{
    return QSqlDatabase::database();
}
